<template>
  <div class="selector-modal-body">
    <!-- 左侧：用户数据源（筛选+表格+分页） -->
    <div class="selector-list">
      <!-- 筛选表单 -->
      <el-form :inline="true" :model="searchParams" class="selector-search-bar" @submit.prevent>
        <el-form-item label="账号">
          <el-input v-model="searchParams.userName" placeholder="账号" size="small" clearable />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="searchParams.nickName" placeholder="姓名" size="small" clearable />
        </el-form-item>
        <template v-if="showMore">
          <el-form-item label="手机号">
            <el-input v-model="searchParams.phone" placeholder="手机号" size="small" clearable />
          </el-form-item>
          <el-form-item label="性别">
            <el-select v-model="searchParams.sex" placeholder="性别" size="small" clearable style="width: 90px;">
              <el-option label="男" value="1" />
              <el-option label="女" value="2" />
              <el-option label="未知" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchParams.status" placeholder="状态" size="small" clearable style="width: 90px;">
              <el-option label="正常" value="0" />
              <el-option label="停用" value="1" />
            </el-select>
          </el-form-item>
        </template>
        <el-form-item>
          <el-button type="primary" size="small" @click="fetchUserList">查询</el-button>
          <el-button size="small" @click="resetSearch">重置</el-button>
          <el-button type="text" size="small" @click="showMore = !showMore">
            <span v-if="!showMore">更多条件</span>
            <span v-else>收起</span>
          </el-button>
        </el-form-item>
      </el-form>
      <!-- 表格区 -->
      <div class="selector-table-wrapper">
        <el-table
          ref="tableRef"
          :data="userList"
          style="width: 100%"
          :row-key="row => row.id"
          :highlight-current-row="!multiple"
          @row-click="onRowClick"
          @selection-change="onSelectionChange"
        >
          <el-table-column type="selection" width="48" :selectable="() => true" />
          <el-table-column label="头像" width="60">
            <template #default="{ row }">
              <el-avatar :src="row.avatar" size="36" shape="circle" />
            </template>
          </el-table-column>
          <el-table-column prop="userName" label="账号" />
          <el-table-column prop="nickName" label="姓名" />
          <el-table-column label="性别">
            <template #default="{ row }">
              <span>{{ sexMap[row.sex] || '未知' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="状态">
            <template #default="{ row }">
              <span>{{ statusMap[row.status] || '未知' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="部门">
            <template #default="{ row }">
              <span>{{ row.posts && row.posts.length ? row.posts[0].name : '' }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页区 -->
      <el-pagination
        v-if="total > 0"
        :current-page="pageNum"
        :page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @current-change="handlePageChange"
        @size-change="handleSizeChange"
        class="selector-pagination"
      />
    </div>
    <!-- 右侧：已选列表 -->
    <div class="selector-selected">
      <div class="selected-title">已选择</div>
      <div v-for="item in selectedList" :key="item.id" class="selected-user">
        <el-avatar :src="item.avatar" size="28" shape="circle" />
        <div class="selected-user-info">
          <span class="selected-user-name">{{ item.nickName }}</span>
          <span class="selected-user-account">{{ item.userName }}</span>
        </div>
        <span class="selected-user-remove" @click="removeSelected(item)">×</span>
      </div>
      <div v-if="!selectedList.length" class="empty-selected">暂无选择</div>
    </div>
  </div>
</template>
<script setup>
import { ref, watch, computed, onMounted } from 'vue'
import { listUserApi } from '@/api/system/organize/user.api'
import { nextTick } from 'vue'

// 引入统一的夜间模式样式
import '../Workflow/styles/dark-theme.css'

const props = defineProps({
  multiple: { type: Boolean, default: true },
  selectedList: { type: Array, default: () => [] },
  // 原始人员配置（用于限制模式）
  originalPersonnel: { type: Array, default: () => [] },
  // 是否限制模式
  limitedMode: { type: Boolean, default: false }
})
const emit = defineEmits(['update:selectedList', 'close'])

// 筛选参数
const searchParams = ref({
  userName: '',
  nickName: '',
  phone: '',
  sex: '',
  status: ''
})
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
const userList = ref([])
const tableRef = ref()
const showMore = ref(false)

// 获取用户列表
async function fetchUserList() {
  try {
    const params = {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      ...searchParams.value
    }
    
    // 如果是限制模式，从原始人员配置中筛选
    if (props.limitedMode && props.originalPersonnel && props.originalPersonnel.length > 0) {
      // 从原始人员配置中筛选符合条件的用户
      const filteredUsers = props.originalPersonnel.filter(user => {
        const userName = user.userName || user.account || ''
        const nickName = user.nickName || user.name || ''
        const phone = user.phone || ''
        
        const searchUserName = searchParams.value.userName.toLowerCase()
        const searchNickName = searchParams.value.nickName.toLowerCase()
        const searchPhone = searchParams.value.phone.toLowerCase()
        
        return (userName.toLowerCase().includes(searchUserName) || searchUserName === '') &&
               (nickName.toLowerCase().includes(searchNickName) || searchNickName === '') &&
               (phone.toLowerCase().includes(searchPhone) || searchPhone === '')
      })
      
      // 分页处理
      const start = (pageNum.value - 1) * pageSize.value
      const end = start + pageSize.value
      userList.value = filteredUsers.slice(start, end)
      total.value = filteredUsers.length
      
      return
    }
    
    // 正常模式：调用API获取用户列表
    const response = await listUserApi(params)
    if (response && response.data) {
      userList.value = response.data.rows || []
      total.value = response.data.total || 0
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    userList.value = []
    total.value = 0
  }
}
function resetSearch() {
  searchParams.value = { userName: '', nickName: '', phone: '', sex: '', status: '' }
  pageNum.value = 1
  fetchUserList()
}
function handlePageChange(page) {
  pageNum.value = page
  fetchUserList()
}
function handleSizeChange(size) {
  pageSize.value = size
  pageNum.value = 1
  fetchUserList()
}

// 选中项
const selectedIds = ref([])
const allSelectedUsers = ref([]) // 存储所有已选择的用户
const isInitializing = ref(true) // 添加初始化标志
const isSyncing = ref(false) // 添加同步标志，防止在同步过程中触发onSelectionChange

watch(() => props.selectedList, (val) => {
  console.log('UserSelector - props.selectedList changed:', val)
  // 确保深拷贝，避免引用问题
  allSelectedUsers.value = Array.isArray(val) ? JSON.parse(JSON.stringify(val)) : []
  // 修复：selectedIds应该包含所有已选择用户的ID，而不仅仅是当前页面的
  selectedIds.value = allSelectedUsers.value.map(item => item.id)
  console.log('UserSelector - allSelectedUsers updated:', allSelectedUsers.value)
  
  // 同步更新表格的勾选状态
  nextTick(() => {
    if (tableRef.value && userList.value.length > 0) {
      console.log('UserSelector - Syncing table selection state')
      // 设置同步标志
      isSyncing.value = true
      
      // 先清除所有选中状态
      tableRef.value.clearSelection()
      // 然后设置已选择的行
      userList.value.forEach(row => {
        const isSelected = allSelectedUsers.value.some(selectedUser => selectedUser.id === row.id)
        console.log(`UserSelector - Syncing row ID ${row.id} (${row.nickName}), isSelected: ${isSelected}`)
        if (isSelected) {
          tableRef.value.toggleRowSelection(row, true)
        }
      })
      
      // 清除同步标志
      isSyncing.value = false
    } else {
      console.log('UserSelector - Table not ready for syncing, will sync in fetchUserList')
    }
  })
}, { immediate: true, deep: true })

const sexMap = { '1': '男', '2': '女', '0': '未知' }
const statusMap = { '0': '正常', '1': '停用' }

const selectedList = computed(() => {
  return allSelectedUsers.value
})

function onRowClick(row) {
  if (tableRef.value) {
    tableRef.value.toggleRowSelection(row)
  }
}

function onSelectionChange(selection) {
  console.log('UserSelector - onSelectionChange called:', selection)
  
  // 检查是否是初始化阶段或同步阶段
  if (isInitializing.value || isSyncing.value) {
    console.log('UserSelector - onSelectionChange: Skipping update during initialization or syncing')
    return
  }
  
  // 获取当前页面中所有行的ID
  const currentPageIds = userList.value.map(u => u.id)
  
  // 获取当前页面中选中的ID
  const currentPageSelectedIds = selection.map(s => s.id)
  
  // 计算当前页面中每个用户的选择状态
  const currentPageSelectionMap = {}
  currentPageIds.forEach(id => {
    currentPageSelectionMap[id] = currentPageSelectedIds.includes(id)
  })
  
  console.log('UserSelector - currentPageSelectionMap:', currentPageSelectionMap)
  
  // 更新allSelectedUsers：保留不在当前页面的已选择用户，根据当前页面的选择状态更新
  let updatedAllSelectedUsers = [
    // 保留不在当前页面的已选择用户
    ...allSelectedUsers.value.filter(user => !currentPageIds.includes(user.id)),
    // 添加当前页面中被选中的用户
    ...userList.value.filter(user => currentPageSelectionMap[user.id])
  ]
  
  // 如果是限制模式，验证选择的人员是否在原始配置范围内
  if (props.limitedMode && props.originalPersonnel && props.originalPersonnel.length > 0) {
    const originalIds = new Set(props.originalPersonnel.map(person => person.id))
    const invalidSelections = updatedAllSelectedUsers.filter(user => !originalIds.has(user.id))
    
    if (invalidSelections.length > 0) {
      console.warn('UserSelector - 限制模式下选择了不在原始配置范围内的人员:', invalidSelections)
      // 过滤掉不在原始配置范围内的人员
      updatedAllSelectedUsers = updatedAllSelectedUsers.filter(user => originalIds.has(user.id))
      
      // 更新表格选择状态，取消无效选择
      nextTick(() => {
        if (tableRef.value) {
          tableRef.value.clearSelection()
          userList.value.forEach(row => {
            if (updatedAllSelectedUsers.some(user => user.id === row.id)) {
              tableRef.value.toggleRowSelection(row, true)
            }
          })
        }
      })
    }
  }
  
  // 更新状态
  allSelectedUsers.value = updatedAllSelectedUsers
  // 更新selectedIds为所有已选择用户的ID
  selectedIds.value = allSelectedUsers.value.map(user => user.id)
  emit('update:selectedList', allSelectedUsers.value)
}

function removeSelected(item) {
  allSelectedUsers.value = allSelectedUsers.value.filter(user => user.id !== item.id)
  
  // 更新selectedIds为所有已选择用户的ID
  selectedIds.value = allSelectedUsers.value.map(user => user.id)
  
  emit('update:selectedList', allSelectedUsers.value)
  
  // 自动取消勾选
  nextTick(() => {
    if (tableRef.value) {
      const row = userList.value.find(u => u.id === item.id)
      if (row) tableRef.value.toggleRowSelection(row, false)
    }
  })
}

onMounted(() => {
  console.log('UserSelector - onMounted called')
  console.log('UserSelector - props.selectedList on mount:', props.selectedList)
  // 重置初始化标志
  isInitializing.value = true
  fetchUserList()
})
</script>
<style scoped>
.selector-modal-body {
  display: flex;
  gap: 16px;
  min-height: 480px;
  height: 60vh;
  max-height: 80vh;
  overflow: auto;
}
.selector-list {
  flex: 2;
  background: #f7f8fa;
  border-radius: 6px;
  padding: 12px;
  min-width: 0;
  display: flex;
  flex-direction: column;
  height: 100%;
}
.selector-search-bar {
  margin-bottom: 12px;
  flex-wrap: wrap;
}
.selector-table-wrapper {
  flex: 1;
  min-height: 0;
  overflow: auto;
}
.selector-pagination {
  margin-top: 8px;
  text-align: right;
}
.selector-selected {
  flex: 1;
  background: #f5f7fa;
  border-radius: 6px;
  padding: 12px;
  min-width: 180px;
  display: flex;
  flex-direction: column;
  border-left: 1px solid #e4e7ed;
}
.selected-title {
  font-weight: bold;
  margin-bottom: 8px;
}
.selected-user {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  background: #fff;
  border-radius: 4px;
  padding: 4px 8px;
  box-shadow: 0 1px 2px #eee;
}
.selected-user .el-avatar {
  margin-right: 8px;
}
.selected-user-info {
  flex: 1;
  overflow: hidden;
}
.selected-user-name {
  font-weight: 500;
  font-size: 15px;
  color: #333;
  margin-right: 8px;
}
.selected-user-account {
  color: #888;
  font-size: 13px;
}
.selected-user-remove {
  margin-left: 8px;
  color: #f56c6c;
  cursor: pointer;
}
.empty-selected {
  color: #bbb;
  margin-top: 12px;
}
</style>
